package org.study.es.boot.service;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;
import org.springframework.stereotype.Service;
import org.study.es.boot.entity.ArticleEntity;
import org.study.es.boot.repository.ArticleRepository;

import java.util.*;

/**
 * 类的描述
 *
 * @author Administrator
 * @date 2021-12-30
 */
@Slf4j
@Service
public class ArticleServiceImpl implements ArticleService {
    @Resource
    private ArticleRepository articleRepository;
    @Resource
    private ElasticsearchTemplate elasticsearchTemplate;

    /**
     * 根据 id 查询
     *
     * @param id
     * @return org.study.es.boot.entity.ArticleEntity
     */
    @Override
    public ArticleEntity findById(long id) {
        ArticleEntity articleEntity = null;
        Optional<ArticleEntity> optional = articleRepository.findById(id);
        if (optional.isPresent()) {
            articleEntity = optional.get();
        }
        return articleEntity;
    }

    /**
     * 根据整个实体的所有属性，可能结果为 0 个
     *
     * @param keywords
     * @return java.util.List<org.study.es.boot.entity.ArticleEntity>
     */
    @Override
    public Iterable<ArticleEntity> search(String keywords) {
        Iterable<ArticleEntity> searchResult = articleRepository.findAll();
        return searchResult;
    }

    /**
     * 新增、修改
     *
     * @param articleEntity
     * @return org.study.es.boot.entity.ArticleEntity
     */
    @Override
    public ArticleEntity save(ArticleEntity articleEntity) {
        ArticleEntity save = articleRepository.save(articleEntity);
        return save;
    }

    /**
     * 根据 id 刪除
     *
     * @param id
     * @return org.study.es.boot.entity.ArticleEntity
     */
    @Override
    public Boolean deleteById(long id) {
        Boolean result = Boolean.FALSE;
        Optional<ArticleEntity> optional = articleRepository.findById(id);
        if (optional.isPresent()) {
            articleRepository.delete(optional.get());
            result = Boolean.TRUE;
        } else {
            log.error("id：{} 的索引不存在", id);
        }
        return result;
    }
}
